# coding=utf-8
import json
from datetime import datetime

from flask import jsonify

from blues.cloud import bp
from blues.cloud.base import request_asapi
from database2 import db_exec_many
from model.c_department import find_all_depart
from public.time_utils import get_last_2days_0hour


def record_cms_ecs() -> bool:
    # 初始化一个空字典，稍后遍历depart并调用asapi后，将cpu和mem监控数据填充到res中
    res = {}
    yesterday_0hour, today_0hour = get_last_2days_0hour()

    # 对于专有云，只能通过部门ak sk获取cms信息
    depart_list = find_all_depart()
    for depart in depart_list:
        cloud_id = depart['cloud_id']
        depart_ak = depart['access_key_id']
        depart_sk = depart['access_key_secret']
        depart_id = depart['department']
        depart_name = depart['department_name']
        print(cloud_id, depart_id, depart_name)

        # 获取ASAPI接口数据
        params = {
            "Namespace": "acs_ecs_dashboard",
            "MetricName": "CPUUtilization",
            "Period": "900",
            "StartTime": yesterday_0hour,  # "2023-09-17 00:00:00"
            "EndTime": today_0hour,  # "2023-09-18 00:00:00"
        }

        # 获取cpu使用率
        asapi_data_cpu = request_asapi(cloud_id, "Cms", "2019-01-01", "DescribeMetricList", params, ak=depart_ak,
                                       sk=depart_sk)
        # print(asapi_data_cpu)
        if not asapi_data_cpu:
            return False
        data_points_cpu = json.loads(asapi_data_cpu['Datapoints'])

        # 获取mem使用率
        params['MetricName'] = 'memory_usedutilization'
        asapi_data_mem = request_asapi(cloud_id, "Cms", "2019-01-01", "DescribeMetricList", params, ak=depart_ak,
                                       sk=depart_sk)
        # print(asapi_data_mem)
        if not asapi_data_mem:
            return False
        data_points_mem = json.loads(asapi_data_mem['Datapoints'])

        # 将cpu和mem监控信息填充到字典res中
        for i in data_points_cpu:
            ins_id = i['instanceId']
            cpu_max = i['Maximum']
            cpu_min = i['Minimum']
            cpu_avg = i['Average']
            if i['instanceId'] not in res.keys():
                res[ins_id] = {
                    "cloud_id": cloud_id, "depart_id": depart_id, "depart_name": depart_name,
                    "cpu_max": [cpu_max], "cpu_min": [cpu_min], "cpu_avg": [cpu_avg],
                    "mem_max": [], "mem_min": [], "mem_avg": []
                }
                continue
            res[ins_id]["cpu_max"].append(cpu_max)
            res[ins_id]["cpu_min"].append(cpu_min)
            res[ins_id]["cpu_avg"].append(cpu_avg)

        for i in data_points_mem:
            ins_id = i['instanceId']
            mem_max = i['Maximum']
            mem_min = i['Minimum']
            mem_avg = i['Average']
            if i['instanceId'] not in res.keys():
                res[ins_id] = {
                    "cloud_id": cloud_id, "depart_id": depart_id, "depart_name": depart_name,
                    "cpu_max": [], "cpu_min": [], "cpu_avg": [],
                    "mem_max": [mem_max], "mem_min": [mem_min], "mem_avg": [mem_avg]
                }
                continue
            res[ins_id]["mem_max"].append(mem_max)
            res[ins_id]["mem_min"].append(mem_min)
            res[ins_id]["mem_avg"].append(mem_avg)

    # 将规整到字典里的数据，求max min avg
    for ins_id in res.keys():
        res[ins_id]["cpu_max"] = max(res[ins_id]["cpu_max"]) if res[ins_id]["cpu_max"] else 0
        res[ins_id]["cpu_min"] = min(res[ins_id]["cpu_min"]) if res[ins_id]["cpu_min"] else 0
        if res[ins_id]["cpu_avg"]:
            res[ins_id]["cpu_avg"] = round(
                sum(res[ins_id]["cpu_avg"]) / len(res[ins_id]["cpu_avg"]),
                2
            )
        else:
            res[ins_id]["cpu_avg"] = 0
        res[ins_id]["mem_max"] = max(res[ins_id]["mem_max"]) if res[ins_id]["mem_max"] else 0
        res[ins_id]["mem_min"] = min(res[ins_id]["mem_min"]) if res[ins_id]["mem_min"] else 0
        if res[ins_id]["mem_avg"]:
            res[ins_id]["mem_avg"] = round(
                sum(res[ins_id]["mem_avg"]) / len(res[ins_id]["mem_avg"]),
                2
            )
        else:
            res[ins_id]["mem_avg"] = 0
    # 打印字典，供检查
    for k, v in res.items():
        print(k, v)
    print(len(res))

    # 准备批量插入数据库，先初始化一个空数组，在循环中不断追加
    values_list = []
    for k, v in res.items():
        tmp_tuple = (
            k, v['cpu_max'], v['cpu_min'], v['cpu_avg'], v['mem_max'], v['mem_min'], v['mem_avg'],
            v['cloud_id'], v['depart_id'], v['depart_name'], yesterday_0hour.rstrip(" 00:00:00"), datetime.now())
        values_list.append(tmp_tuple)
    table = 'cms_ecs'
    fields = "instance_id,cpu_max,cpu_min,cpu_avg,mem_max,mem_min,mem_avg,cloud_id,depart_id,depart_name,`date`,record_time"
    # 使用上面的数据，批量插入db
    db_success = db_exec_many(table, fields, values_list)
    if not db_success:
        return False
    return True


@bp.route('/api/v1/cloud/record_cms_ecs', methods=['POST'])
def record_cms_ecs_api():
    success = record_cms_ecs()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})
